package com.gdsz.libbasic.utils.view

import android.content.Context
import android.content.res.Resources
import android.os.Build
import android.util.DisplayMetrics
import android.util.Log

import android.util.TypedValue
import android.view.View
import android.view.ViewGroup.MarginLayoutParams
import android.view.WindowManager
import android.widget.Toast
 
import java.util.Locale

object DisplayUtil {
    /**
     * dp转px
     */
    @JvmStatic
    fun dp2px(context: Context, dpVal: Float): Float {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dpVal, context.resources.displayMetrics
        )
    }
    @JvmStatic
    fun dip2px(context: Context, dipValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dipValue * scale + 0.5f).toInt()
    }

    /**
     * sp转px
     */
    @JvmStatic
    fun sp2px(context: Context, spVal: Float): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_SP,
            spVal, context.resources.displayMetrics
        ).toInt()
    }


    /**
     * 获取 显示信息
     */
    @JvmStatic
    fun getDisplayMetrics(context: Context): DisplayMetrics {
        return context.resources.displayMetrics
    }

    /**
     * 打印 显示信息
     */
    @JvmStatic
    fun printDisplayInfo(context: Context): DisplayMetrics {
        val dm = getDisplayMetrics(context)
        val sb = StringBuilder()
        sb.append("_______  显示信息:  ")
        sb.append("\ndensity         :").append(dm.density)
        sb.append("\ndensityDpi      :").append(dm.densityDpi)
        sb.append("\nheightPixels    :").append(dm.heightPixels)
        sb.append("\nwidthPixels     :").append(dm.widthPixels)
        sb.append("\nscaledDensity   :").append(dm.scaledDensity)
        sb.append("\nxdpi            :").append(dm.xdpi)
        sb.append("\nydpi            :").append(dm.ydpi)
        Log.d("MyDisplay->",sb.toString())
        return dm
    }
    @JvmStatic
    fun getAndroidScreenProperty(activity: Context) {
        val wm = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val dm = DisplayMetrics()
        wm.defaultDisplay.getMetrics(dm)
        val width = dm.widthPixels // 屏幕宽度（像素）
        val height = dm.heightPixels // 屏幕高度（像素）
        val density = dm.density // 屏幕密度（0.75 / 1.0 / 1.5）
        val densityDpi = dm.densityDpi // 屏幕密度dpi（120 / 160 / 240）
        // 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
        val screenWidth = (width / density).toInt() // 屏幕宽度(dp)
        val screenHeight = (height / density + 0.5f).toInt() // 屏幕高度(dp)
        Log.d("MyDisplay->","屏幕宽度（像素）：$width")
        Log.d("MyDisplay->","屏幕高度（像素）：$height")
        Log.d("MyDisplay->","屏幕密度（0.75 / 1.0 / 1.5 / 2 / 3 / 4）：$density")
        Log.d("MyDisplay->","屏幕密度dpi（0-120(ldpi) / 120-160(mdpi) / 160-240(hdpi) / 240-320(xhdpi) / 320-480(xxhdpi) / 480-640(xxxhdpi)）：$densityDpi")
        Log.d("MyDisplay->","屏幕宽度（dp）：$screenWidth")
        Log.d("MyDisplay->","屏幕高度（dp）：$screenHeight")
    }

    @JvmStatic
    fun getScreenSizeWidth(context: Context): Int {
        val wm = context
            .getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val metric = DisplayMetrics()
        wm.defaultDisplay.getMetrics(metric)
        val width = metric.widthPixels // 屏幕宽度（像素）
        Log.d("MyDisplay->",width.toString() + "")
        return width
    }

    @JvmStatic
    fun getScreenSizeHeight(context: Context): Int {
        val wm = context
            .getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val metric = DisplayMetrics()
        wm.defaultDisplay.getMetrics(metric)
        return metric.heightPixels
    }



    fun px2dip(context: Context, pxValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (pxValue / scale + 0.5f).toInt()
    }

    @JvmStatic
    fun getStatusBarHeight(context: Context): Int {
        var result = 0
        val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            result = context.resources.getDimensionPixelSize(resourceId)
        }
        return result
    }

    /**
     * 隐藏迈冲android系统底部虚拟栏
     *
     * @param context
     * @return
     */
    fun hideMCNavBar(context: Context): Boolean {
        if (!hasNavigationBar(context)) {
            return true
        }
        var ishide: Boolean
        try {
            val command: String =
                "LD_LIBRARY_PATH=/vendor/lib:system/lib service call activity 42 s16 com.android.systemui"
            val proc = Runtime.getRuntime().exec(arrayOf("su", "-c", command))
            proc.waitFor()
            ishide = true
        } catch (ex: Exception) {
            Toast.makeText(
                context.applicationContext, ex.message,
                Toast.LENGTH_LONG
            ).show()
            ishide = false
        }
        return ishide
    }

    /**
     * 显示迈冲android系统底部虚拟栏
     *
     * @return
     */
    fun showMCNavBar(context: Context): Boolean {
        if (!hasNavigationBar(context)) {
            return true
        }
        var isshow: Boolean
        try {
            val command: String =
                "LD_LIBRARY_PATH=/vendor/lib:system/lib am startservice -n com.android.systemui/.SystemUIService"
            val proc = Runtime.getRuntime().exec(arrayOf("su", "-c", command))
            proc.waitFor()
            isshow = true
        } catch (e: Exception) {
            isshow = false
            e.printStackTrace()
        }
        return isshow
    }

    /**
     * 判断是否存在虚拟按键
     *
     * @return
     */
    fun hasNavigationBar(context: Context): Boolean {
        var hasNavigationBar = false
        val rs = context.resources
        val id = rs.getIdentifier("config_showNavigationBar", "bool", "android")
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id)
        }
        try {
            val systemPropertiesClass = Class.forName("android.os.SystemProperties")
            val m = systemPropertiesClass.getMethod("get", String::class.java)
            val navBarOverride = m.invoke(systemPropertiesClass, "qemu.hw.mainkeys") as String
            if ("1" == navBarOverride) {
                hasNavigationBar = false
            } else if ("0" == navBarOverride) {
                hasNavigationBar = true
            }
        } catch (e: Exception) {
        }
        return hasNavigationBar
    }

    fun setMargin(v: View, l: Int, t: Int, r: Int, b: Int) {
        if (v.layoutParams is MarginLayoutParams) {
            val p = v.layoutParams as MarginLayoutParams
            p.setMargins(l, t, r, b)
            v.requestLayout()
        }
    }

    fun getNavigationBarHeight(context: Context): Int {

        if (isHuaWei()) {
            return if (!hasNavigationBar(context)) {
                val resources: Resources = context.resources
                val resourceId: Int =
                    resources.getIdentifier("navigation_bar_height", "dimen", "android")
                val height: Int = resources.getDimensionPixelSize(resourceId)
                Log.v("navigation bar>>>", "height:$height")
                height
            } else {
                0
            }
        }

        val resources: Resources = context.resources
        val resourceId: Int = resources.getIdentifier("navigation_bar_height", "dimen", "android")
        val height: Int = resources.getDimensionPixelSize(resourceId)
        Log.v("navigation bar>>>", "height:$height")
        return height

    }


    private fun getPhoneBrand(): String {
        val manufacturer = Build.MANUFACTURER
        return if (manufacturer != null && manufacturer.isNotEmpty()) {
            manufacturer.lowercase(Locale.getDefault())
        } else {
            "unknown"
        }
    }

    fun isHuaWei(): Boolean {
        val phoneBrand = getPhoneBrand()
        return (phoneBrand.contains("HUAWEI") || phoneBrand.contains("OCE")
                || phoneBrand.contains("huawei") || phoneBrand.contains("honor"))
    }
}